//
//  C11NetConnector.m
//  精通Objective-C
//
//  Created by 花强 on 2017/12/26.
//  Copyright © 2017年 花强. All rights reserved.
//

#import "C11NetConnector.h"

//通过扩展声明，提供属性
@interface C11NetConnector()<NSURLConnectionDataDelegate>

@property NSURLRequest * request;
@property BOOL finishedLoading;
@property NSURLConnection * connector;
@property NSMutableData * receiveData;

@end;

@implementation C11NetConnector

-(id)initWithRequest:(NSURLRequest *)request{
    if (self = [super init]) {
        _request = request;
        
        //通过合适的内存存储结构，创建URL缓存
        NSURLCache * URLCache = [[NSURLCache alloc] init];
        [URLCache setMemoryCapacity:CACHE_MEMARY_SIZE];
        [NSURLCache setSharedURLCache:URLCache];
        
        //创建连接并开始下载资源数据
        _connector = [NSURLConnection connectionWithRequest:request delegate:self];
    }
    return self;
}

-(void)reloadRequest{
    self.finishedLoading = NO;
    self.connector = [NSURLConnection connectionWithRequest:self.request delegate:self];
}

#pragma mark -
#pragma mark Delegate methods
//当连接能够对请求做出回应时，会发送该消息
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    if (self.receiveData != nil) {
        //将receiveData对象长度置0，从而丢弃了通过上一个请求接收的数据
        [self.receiveData setLength:0];
    }
}
//在连接将回应存储到缓存前，会发送该消息
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{
    //使用这个方法能够修改该回应，也可以阻止它被存储到缓存中
    NSURLResponse * response = [cachedResponse response];
    NSURL * url = [response URL];
    if ([[url scheme] isEqualToString:HTTP_SCHEME] || [[url scheme] isEqualToString:HTTPS_SCHEME]) {
        NSLog(@"Downloaded data,caching response");
        return cachedResponse;
    }else{
        NSLog(@"Downloaded data,not caching response");
        return nil;
    }
}
//接收资源时，，会发送该消息；若以递增的方式接收数据，在单个请求中该方法可能会被调用多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    if (self.receiveData != nil) {
        [self.receiveData appendData:data];
    }else{
        self.receiveData = [[NSMutableData alloc] initWithData:data];
    }
}
//当连接成功完成加载数据操作时，会发送该消息
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSUInteger length = [self.receiveData length];
    NSLog(@"Download %lu bytes from request %@",length,self.request);
    
    //加载数据后，设置退出运行循环的标记
    self.finishedLoading = YES;
}
//当连接加载数据失败时，会发送该消息
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"Error loading request %@",[error localizedDescription]);
    self.finishedLoading = YES;
}


-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
    //使用用户名 密码 创建了一个证书
    NSURLCredential * credential = [NSURLCredential credentialWithUser:@"TestUser" password:@"TestPassword" persistence:NSURLCredentialPersistenceForSession];
    //使用证书回应连接的身份认证质询
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

@end
